package com.gitee.wsl.doc.prosemirror.history.ext

import com.gitee.wsl.doc.prosemirror.history.HistoryPluginSpec
import com.gitee.wsl.doc.prosemirror.history.bean.HistoryPluginData
import com.gitee.wsl.doc.prosemirror.history.bean.HistoryState
import com.gitee.wsl.doc.prosemirror.history.historyKey
import com.gitee.wsl.doc.prosemirror.history.mustPreserveItems
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.state.Transaction


/** Apply the latest event from one branch to the document and shift the event
 * onto the other branch.
 */
fun HistoryState.histTransaction(state: EditorState, redo: Boolean): Transaction? {
    val history = this
    val preserveItems = state.mustPreserveItems()
    val histOptions = (historyKey.get(state)!!.spec as HistoryPluginSpec).config
    val pop = (if (redo) history.undone else history.done).popEvent(state, preserveItems) ?: return null

    val selection = pop.selection.resolve(pop.transform.doc)
    val added = (if (redo) history.done else history.undone)
        .addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems)

    val newHist = HistoryState(
        if (redo) added else pop.remaining,
        if (redo) pop.remaining else added,
        null,
        0,
        -1
    )
    return pop.transform.setSelection(selection)
        .setMeta(historyKey, HistoryPluginData(redo, historyState = newHist))
}
